<?php

namespace Beerus\Modules\DesignerCompetition2020\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\DesignerCompetition2020\DesignerVote;
use Doraemon\cache\DesignerCompetition2020\DesignerVote as cDesignerVote;
use Doraemon\model\Article;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerEquity;
use Doraemon\model\DesignerCompetition\Confirmation;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\DesignerCompetition\FinalReview;
use Doraemon\model\DesignerCompetition\NavigatorScore;
use Doraemon\service\DesignerCompetition2020\SignService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;

/**
 * 参赛作品头图设置
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class VoteController extends Controller
{
    const PAGE_SIZE = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_params = $request->all();
        $condition = [
            'house_audit' => DesignerAwardSign2020::BEGIN_AUDIT_PASS,
        ];

        if (!empty($request_params['uid'])) {
            $condition['uid'] = $request_params['uid'];
        }

        if (!empty($request_params['nick'])) {
            $condition['nick[~]'] = $request_params['nick'];
        }

        if (!empty($request_params['id'])) {
            $condition['id'] = $request_params['id'];
        }

        $order_type = empty($request_params['order_type']) ? 'real_vote' : $request_params['order_type'];
        $condition['ORDER'] = [$order_type => 'DESC'];

        return $content
            ->header('投票作品列表')
            ->row($this->indexGrid($condition));
    }

    public function indexGrid($condition)
    {
        Admin::script($this->jumpScript());

        $lists = DesignerAwardSign2020::select('*', $condition);

        unset($condition['ORDER']);
        $total = DesignerAwardSign2020::count($condition);

        $votes = DesignerAwardSign2020::select('*', [
            'house_audit' => DesignerAwardSign2020::BEGIN_AUDIT_PASS
        ]);
        $show_votes = array_column($votes, 'show_vote');
        array_multisort($show_votes, SORT_DESC, $votes);
        $map_show = array_flip(array_column($votes, 'article_id'));

        $real_votes = array_column($votes, 'real_vote');
        array_multisort($real_votes, SORT_DESC, $votes);
        $map_real = array_flip(array_column($votes, 'article_id'));

        if (!empty($lists)) {
            foreach ($lists as &$item) {
                $item['user_type'] = SignService::USER_TYPE[$item['user_type']];
                $item['real_rank'] = $map_real[$item['article_id']] + 1;
                $item['show_rank'] = $map_show[$item['article_id']] + 1;

                // 作品链接
                if ($item['channel'] == DesignerAwardSign2020::FROM_OWNER) {
                    $article_info = Article::getArticle($item['article_id']);
                    $item['work_name'] = empty($article_info) ? '作品名称无' : $article_info['title'];
                    $item['link'] = Hhzurl::getDomain() . "/bangyang/{$item['article_id']}.html";
                } elseif ($item['channel'] == DesignerAwardSign2020::FROM_DESIGNER) {
                    $item['link'] = Hhzurl::getDomain() . "/designer/game/2020/production-detail?id={$item['id']}";
                }

                $live_photos = json_decode($item['live_photos'], true);
                $pic = ImgUrl::getUrl(
                    ImgUrl::APPTYPE_APP,
                    $live_photos[0]['pic_id'],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE
                );

                $item['head_img'] = empty($item['head_img']) ? $pic : ImgUrl::getUrl(
                    ImgUrl::APPTYPE_APP,
                    $item['head_img'],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE
                );
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '成员UID')->placeholder('请输入用户uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('nick', '成员昵称')->placeholder('请输入用户昵称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('order_type', '排序方式')->select([
                            'real_vote' => '按实际票数由高到低',
                            'show_vote' => '按展示票数由高到低'
                        ])->default('real_vote');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('id', '报名id')->placeholder('请输入报名id');
                    });
                    $filter->expand();
                });

                $grid->column('id', '报名id')->width(80);
                $grid->column('article_id', '作品id')->width(100);
                $grid->column('user_info', '设计师')->width(260)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a class="jump_user" href="javascript:void(0);"> ' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });

                $grid->column('work_link', '作品')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa" href="javascript:layer.open({type: 2,
                    title: \'预览\', maxmin: true, area: [\'650px\', \'700px\'],
                    content: \'' . $this->link . '\' });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->head_img}'>";

                    if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
                        return implode('<br/>', [$img, $open]);
                    } elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
                        return implode('<br/>', [$img, $open]);
                    }
                });

                $grid->column('show_vote', '展示票数')->width(150);
                $grid->column('show_rank', '展示排名')->width(150);
                $grid->column('real_vote', '实际票数')->width(150);
                $grid->column('real_rank', '实际排名')->width(100);

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();

                    $url = Hhzurl::getDomain(). "/designer/game/2020/set-cover?id=".$actions->row->id;
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-picture-o" href="javascript:layer.open({
                                type: 2,
                                title: \'选择参赛作品封面\',
                                maxmin: true,
                                area: [\'800px\', \'600px\'],
                                content: \''.$url.'\'
                            });">选择封面</a></p>');
                });
            }
        );

        return $gridList;
    }

    private function jumpScript()
    {
        return <<<SCRIPT
        // 用户详情跳转
        $('.jump_user').unbind('click').click(function(){
            let win = window.open('http://manage.haohaozhu.me/','用户详情','name=用户详情');
            win.openapp('/User/Oauthadmin/detail/uid/608209','user_detail608209','用户详情');
        });

        $('.btn-xs').hide();

        $("input[name='grid-radio-audit_status']").change(
		function() {
		        id = $(this).parents('.grid-radio-audit_status')[0].getAttribute('data-key');
                var audit_status = $(this).val();

                $.ajax({
                    url:'/admin/DesignerCompetition2020/audit/' + id,
                    type:"POST",
                    data: {_method:"PUT", audit_status: audit_status},
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
	    });
SCRIPT;
    }

    public function edit(Content $content, $id = 0)
    {
        $header = '修改票数';
        $tab = new Tab();
        $tab->add('用户票数信息', self::editAction($id));
        return $content->header($header)
            ->breadcrumb([
                'text' => '投票作品列表 ',
                'url' => route('vote.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($id = 0)
    {
        $data = DesignerAwardSign2020::get('*', ['id' => $id]);
        $article_id = $data['article_id'];
        $form = new Form($data);
        $form->hidden('id');
        $form->text('uid', '用户UID')->setWidth(4, 2)->readOnly();
        $form->text('nick', '用户昵称')->setWidth(4, 2)->readOnly();
        $form->text('article_id', '作品id')->setWidth(4, 2)->readOnly();
        $form->text('work_name', '作品名称')->setWidth(4, 2);
        $form->textarea('work_intro', '作品介绍')->rows(15)->setWidth(10, 2);
        $form->text('total_price', '总报价')->setWidth(4, 2);
        $form->select('house_model', '报名户型')->setWidth(4, 2)->options(SignService::HOUSE_MODEL);
        $form->text('show_vote', '展示票数')->setWidth(4, 2)->required('不能为空');
        $form->text('real_vote', '实际票数')->setWidth(4, 2)->readOnly();
        $form->action("/admin/DesignerCompetition2020/vote/save/{$id}/{$article_id}");

        return $form->render();
    }

    public function saveData(Request $request, $id, $article_id)
    {
        $request = $request->all();

        cDesignerVote::setArticleShowVote($article_id, $request['show_vote']);
        DesignerAwardSign2020::updateInfo($id, [
            'show_vote' => $request['show_vote'],
            'work_name' => $request['work_name'],
            'total_price' => $request['total_price'],
            'work_intro' => $request['work_intro'],
            'house_model' => $request['house_model']
        ]);
        $data = [
            'house_model' => $request['house_model']
        ];
        Confirmation::update($data, [
            'sign_id' => $id
        ]);
        FinalReview::update($data, [
            'sign_id' => $id
        ]);
        NavigatorScore::update($data, [
            'sign_id' => $id
        ]);

        $success = new MessageBag([
            'title' => '修改成功'
        ]);

        return redirect('/admin/DesignerCompetition2020/vote')->with(compact('success'));
    }
}
